package com.shop.cloud.controller.system;

import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.shop.cloud.common.TreeNode;
import com.shop.cloud.common.mapper.JsonMapper;
import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.domain.system.SysResource;
import com.shop.cloud.domain.system.SysRoleResource;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.MagicPermission;
import com.shop.cloud.model.request.DeleteSysUserRequest;
import com.shop.cloud.model.request.GetSysResourceListRequest;
import com.shop.cloud.model.response.GetSysResourceListResponse;
import com.shop.cloud.model.response.ObjectDataResponse;
import com.shop.cloud.service.hongfu.ILogService;
import com.shop.cloud.service.system.ISysResourceService;
import com.shop.cloud.service.system.ISysRoleResourceService;
import com.shop.cloud.util.DateUtils;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

@RestController
@RequestMapping(value = "resource")
public class SysResourceController extends BaseController {

	private static final Logger logger = Logger
			.getLogger(SysResourceController.class);

	@Autowired
	private ISysResourceService sysResourceService;

	@Autowired
	private ISysRoleResourceService sysRoleResourceService;
	
	@Autowired
	private ILogService logService;
	
	
	/**
	 * 
	 * @param 查詢所有菜單數據
	 * @param gmc
	 * @param sysResource 菜單
	 * @return
	 */
	//@MagicPermission
	@ApiOperation(value = "查询所有菜單" , notes="查询所有菜單")
	@RequestMapping(value = "queryResource", method = {RequestMethod.POST}  )
	@ResponseBody
	public ObjectDataResponse<List<SysResource>> queryResource(@CurrentUserId Long userId,@RequestBody SysResource sysResource){
		logService.addLog(userId, 0, "查询菜單");
		sysResource.setIsMenu(1);
		//得到所有集合數據
		List<SysResource> sysResourceList=sysResourceService.find(sysResource);
		//創建集合 存放一級菜單
		List<SysResource> dataOne = new ArrayList<SysResource>();
		//創建集合 存放二級菜單
		List<SysResource> dataTwo = null;
		
		for(int i=0;i<sysResourceList.size();i++){
			//判斷是否為一級
			if (sysResourceList.get(i).getParentId() == null) {
				dataTwo = new ArrayList<SysResource>();
				for(int j=0;j<sysResourceList.size();j++){
					//父類id等於子類parentid
					if(sysResourceList.get(i).getId().equals(sysResourceList.get(j).getParentId())){
						dataTwo.add(sysResourceList.get(j));
					}
				}
				sysResourceList.get(i).setResources(dataTwo);
				dataOne.add(sysResourceList.get(i));
			}
		}
		return new ObjectDataResponse<List<SysResource>>(dataOne);
	}
	
	//@MagicPermission
	@ApiOperation(value = "查询职位菜單權限" , notes="查询职位菜單權限")
	@RequestMapping(value = "queryResourceByPositionId", method = {RequestMethod.POST}  )
	@ResponseBody
	public ObjectDataResponse<List<SysResource>> queryResourceByPositionId(@CurrentUserId Long userId,@RequestBody SysResource sysResource){
		
		List<SysResource> datas = sysResourceService.findByUserId(sysResource);
		
		return new ObjectDataResponse<List<SysResource>>(datas);
	}
	
	//@MagicPermission
	@ApiOperation(value = "修改角色菜單權限" , notes="修改角色菜單權限")
	@RequestMapping(value = "UpdateRoleResourceByRoleId", method = {RequestMethod.POST}  )
	@ResponseBody
	public ObjectDataResponse<Integer> UpdateRoleResourceByRoleId(@CurrentUserId Long userId,@RequestBody SysRoleResource sysRoleResource){
		
		int success = sysRoleResourceService.updateRoleResource(sysRoleResource);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@ApiOperation(value = "左侧菜單" , notes="菜單")
	@RequestMapping(value = "LeftMenu", method = {RequestMethod.POST}  )
	@ResponseBody
	public ObjectDataResponse<List<SysResource>> LeftMenu(@CurrentUserId Long userId,@RequestBody SysResource sysResource){
		sysResource.setIsMenu(1);
		sysResource.setUserId(userId);
		List<SysResource> sysResourceList = sysResourceService.findByUser(sysResource);
		//創建集合 存放一級菜單
				List<SysResource> dataOne = new ArrayList<SysResource>();
				//創建集合 存放二級菜單
				List<SysResource> dataTwo = null;
				
				for(int i=0;i<sysResourceList.size();i++){
					//判斷是否為一級
					if (sysResourceList.get(i).getParentId() == null) {
						dataTwo = new ArrayList<SysResource>();
						for(int j=0;j<sysResourceList.size();j++){
							//父類id等於子類parentid
							if(sysResourceList.get(i).getId().equals(sysResourceList.get(j).getParentId())){
								dataTwo.add(sysResourceList.get(j));
							}
						}
						sysResourceList.get(i).setResources(dataTwo);
						dataOne.add(sysResourceList.get(i));
					}
				}

		return new ObjectDataResponse<List<SysResource>>(dataOne);
	}
	
	@MagicPermission
	@RequestMapping(value = "find")
	@ResponseBody
	public Response find(String parentId,HttpServletRequest request) {
		Map<String, Object> params = getParamMap(request);
		if (StringUtils.isEmpty(parentId) || parentId.equals("#")) {
			params.put("parentId", null);
		}
		params.put("orderBy", "sort_no");
		List<SysResource> departments = sysResourceService.find(params);
		List<SysResource>  sysResourceService=TreeNode.tree(departments);
		return ResponseUtil.ok(sysResourceService);
	}

	@MagicPermission
	@RequestMapping(value = "findRoleResource", method = RequestMethod.POST)
	@ResponseBody
	public Response findRoleResource(Long roleId,HttpServletRequest request) {
		Map<String, Object> paramsMap=getParamMap(request);
		if("#".equals(paramsMap.get("parentId"))){
			paramsMap.remove("parentId");
		}
		paramsMap.put("status", 0);
		Map<String, Object> dataMap=new HashMap<String, Object>();
		List<SysResource> datas =sysResourceService.find(paramsMap);
		List<String> resourceIds=new ArrayList<String>();
		if(roleId!=null){
			resourceIds=sysResourceService.findRoleResource(roleId);
		}
		TreeNode root = new TreeNode();
		HashMap<Long, TreeNode> nodeList = new HashMap<Long, TreeNode>();
		for (Iterator<SysResource> it = datas.iterator(); it.hasNext();) {
			SysResource entity = it.next();
			TreeNode node = new TreeNode();
			node.id = entity.getId();
			node.text = entity.getName();
			node.parentId = entity.getParentId();
			nodeList.put(node.id, node);
		}
		Set<Map.Entry<Long, TreeNode>> entrySet = nodeList.entrySet();
		for (Iterator<Map.Entry<Long, TreeNode>> iterator = entrySet.iterator(); iterator.hasNext();) {
			Map.Entry<Long, TreeNode> entry = iterator.next();
			TreeNode node = entry.getValue();
			if (node.parentId==null) {
				root.addChild(node);
			} else {
				if(node.parentId!=null && node!=null){
					resourceIds.remove(node.parentId);
				}
				System.out.println(JsonMapper.nonDefaultMapper().toJson(node));
				nodeList.get(node.parentId).addChild(node);
			}
		}
		dataMap.put("checkData", resourceIds);
		dataMap.put("treeData", root.children);
		root.sortChildren(TreeNode.SysResourceComparatorEnum.ID);
		return ResponseUtil.ok(dataMap);
	}

	//@MagicPermission
	@RequestMapping(value = "list")
	@ResponseBody
	public Response list(@CurrentUserId Long userId,HttpServletRequest request, HttpServletResponse response, @RequestBody GetSysResourceListRequest getSysResourceListRequest) {
		Map<String, Object> params = null;
		List<GetSysResourceListResponse> datas = new ArrayList<GetSysResourceListResponse>();
		List<SysResource> sysResources = null;
		
		params.put("parent_id", null);
		
		sysResourceService.find(params);
		
		return ResponseUtil.ok(datas);
	}

	@RequestMapping(value = "list2")
	@ResponseBody
	public Response list2(HttpServletRequest request) {
		Map<String, Object> params = getPageMap(request);
		return ResponseUtil.ok(sysResourceService.list(params));
	}
	
	@MagicPermission
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public Response update(@CurrentUserId Long userId,HttpServletRequest request, SysResource sysResource) {
		Date date = DateUtils.getSysDate();
		sysResource.setUpdateDate(date);
		sysResource.setUpdateUser(userId);	
		sysResourceService.update(sysResource);
		return ResponseUtil.ok();
	}

	@MagicPermission
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public Response add(@CurrentUserId Long userId,HttpServletRequest request, SysResource sysResource,
			String roleIds) {
		Date date = DateUtils.getSysDate();
		sysResource.setCreateDate(date);
		sysResource.setUpdateDate(date);
		sysResource.setUpdateUser(userId);
		sysResource.setCreateUser(userId);
		sysResourceService.insert(sysResource, roleIds);
		return ResponseUtil.ok();
	}

	@MagicPermission
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Response delete(SysResource sysResource) {
		if(sysResource.getId()==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		sysResource.setStatus(1);
		sysResourceService.deleteResource(sysResource);
		return ResponseUtil.ok();
	}

}